import { Button, Empty, Modal, Typography } from 'antd'
import { forwardRef, memo, useEffect, useImperativeHandle, useRef, useState } from 'react'
import addmonitor from '@/assets/addmonitor.png'
import { has_datas, monitorList } from '@/api/home'
import { openCompanyDetail } from 'hs-react-company'
import { useImmer } from 'use-immer'
const { Text } = Typography
import { MonitorsList } from '@hs-server/components'
import { addmonitorsitems, deletemonitors } from '../../../api/home'
import Monitoring_successful from '/src/assets/Monitoring_successful.png'

const CompanyModel = (_props: any, ref: any) => {
  const { isModal } = _props
  const [source_id, setsource_id] = useState<any>('')

  const [isModalOpen, setIsModalOpen] = useState(false)

  const [ismonitor, setismonitor] = useState(false)

  const conitorsListRef: any = useRef({})

  const [company_code, setcompany_code] = useState<any>('')

  const [CompanyModelpage, setCompanyModelpage] = useImmer<any>({
    current: 1,
    pageSize: 1
  })

  const [List, setList]: any = useState({})
  const calcel = () => {
    setIsModalOpen(false)
  }
  const showModal = (id: any) => {
    setsource_id(id)
    setIsModalOpen(true)
    getmonitorList()
  }

  const minusPage = () => {
    setCompanyModelpage((prev: { current: number }) => {
      prev.current--
    })
  }
  const addPage = () => {
    if (CompanyModelpage?.current * CompanyModelpage.pageSize < List.total) {
      setCompanyModelpage((prev: { current: number }) => {
        prev.current++
      })
    }
  }

  const gethas_datas = async (items: any) => {
    const res = await has_datas({ data_ids: items?.map((its: any) => its.company_code) })
    setList((prev: any) => {
      const newItems = prev.items.map((its: any) => {
        its.has_monitored = res[its.company_code]
        return its
      })
      return { items: newItems }
    })
    isModal()
  }

  const getmonitorList = () => {
    const data: any = {
      page: CompanyModelpage.current,
      page_size: CompanyModelpage.pageSize,
      id: source_id
    }
    monitorList(data).then((res: any) => {
      setList(res)
      gethas_datas(res.items)
    })
  }

  const addmonitorsitem = (id: any, name: any) => {
    if (!ismonitor) {
      addmonitors_items(id, name)
    } else delemonitors(id)
  }

  const addmonitors_items = async (id: any, name: any) => {
    await addmonitorsitems({ data_id: company_code, list_id: id, data_name: name })
    getmonitorList()
  }

  const getsource = (company_code: any, ismonitor: boolean) => {
    setcompany_code(company_code)
    setismonitor(ismonitor)
    conitorsListRef.current.showModal(!ismonitor ? null : company_code)
  }

  const delemonitors = (id: any) => {
    deletemonitors({ list_id: id, data_id: company_code })
    getmonitorList()
  }

  useEffect(() => {
    getmonitorList()
  }, [CompanyModelpage])

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    []
  )

  return (
    <Modal title="" open={isModalOpen} onCancel={calcel} width={600} centered footer={null}>
      <div className="px-40px">
        {List.items?.length ? (
          List.items.map((its: any, index: number) => {
            return (
              <div key={index} className="company-item flex items-center justify-between mt-20px">
                <div className="company-item-title text-blue cursor-pointer">
                  <Text
                    className="warning-name w-100% mr-10px  text-blue cursor-pointer"
                    ellipsis={{ tooltip: true }}
                    onClick={() => openCompanyDetail(its.company_code)}>
                    {its.company_name}
                  </Text>
                </div>
                <div className="flex items-center">
                  <div className="flex items-center cursor-pointer" onClick={() => getsource(its.company_code, its.has_monitored)}>
                    <img className="w-14px h-14px ml-11px" src={its.has_monitored ? Monitoring_successful : addmonitor} alt="" />
                    <div className="ml-7px">{its.has_monitored ? '已监测' : '加监测'}</div>
                  </div>
                </div>
              </div>
            )
          })
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
        <div className="flex items-center mt-50px justify-end">
          <Button size="small" className="mr-10px" type="primary" onClick={minusPage} disabled={CompanyModelpage?.current === 1}>
            上一页
          </Button>
          <div className="mr-20px">{` ${CompanyModelpage?.current} / ${Math.ceil(2 / 10)} `}</div>
          <Button size="small" type="primary" onClick={addPage} disabled={CompanyModelpage?.current * CompanyModelpage?.pageSize >= 2}>
            下一页
          </Button>
        </div>
      </div>
      <MonitorsList ref={conitorsListRef} addmonitorsitem={addmonitorsitem} />
    </Modal>
  )
}

export default memo(forwardRef(CompanyModel))
